// src/services/authService.js
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const config = require('../config');

/**
 * 注册新用户
 * @param {Object} data - 用户数据
 * @returns {Object} - 用户ID和JWT
 */
exports.register = async ({ username, email, password }) => {
  if (!username || !password) throw new Error('Username and password are required');
  const existingUser = await User.findOne({ username });
  if (existingUser) throw new Error('Username already exists');
  const user = new User({ username, email, password });
  await user.save();
  const token = jwt.sign({ id: user._id, username }, config.jwtSecret, { expiresIn: '7d' });
  return { userId: user._id, token };
};

/**
 * 用户登录
 * @param {Object} data - 登录凭据
 * @returns {Object} - 用户ID和JWT
 */
exports.login = async ({ username, password }) => {
  const user = await User.findOne({ username });
  if (!user) throw new Error('User not found');
  const isMatch = await user.comparePassword(password);
  if (!isMatch) throw new Error('Invalid password');
  const token = jwt.sign({ id: user._id, username }, config.jwtSecret, { expiresIn: '7d' });
  return { userId: user._id, token };
};